package com.woniuxy.yygy.gateway.filter;


import com.alibaba.fastjson.JSONObject;
import com.woniuxy.yygh.common.helper.JwtHelper;
import com.woniuxy.yygh.common.result.Result;
import com.woniuxy.yygh.common.result.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;


/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 全局过滤器 ，统一处理会员登录与外部不允许访问的服务
 * <P> Date: 2022/3/4:19:13
 * <P> Description:
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    Logger logger = LoggerFactory.getLogger(AuthGlobalFilter.class);

    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        //得到当前url路径
        String path = request.getURI().getPath().intern();

        //打印信息
        urlPathPrint(path, request);

        //内部服务接口，不允许外部访问
        if (antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            return out(response, ResultCodeEnum.PERMISSION);
        }


        //TODO api接口，异步请求，校验用户必须登录 中间是auth的才拦截
        if (antPathMatcher.match("/api/**/auth/**", path)) {
            //普通用户才获取token
            //从token中获取userid
            Long userId = this.getUserId(request);
            //如果为空
            if (StringUtils.isEmpty(userId)) {
                ServerHttpResponse response = exchange.getResponse();
                return out(response, ResultCodeEnum.LOGIN_AUTH);
            }
        }
        //放行
        return chain.filter(exchange);
    }

    private void urlPathPrint(String path, ServerHttpRequest request) {

        logger.info(" ::::::访问路径::::::{}" + path);

//        try {
//            MultiValueMap<String, String> queryParams = request.getQueryParams();
//            System.out.println("当前参数：");
//            queryParams.keySet().stream().forEach(key-> System.out.println(key  + " -- "+ queryParams.get(key)));
//            System.out.println("end");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }


    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * api接口鉴权失败返回数据
     *
     * @param response
     * @return
     */
    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 获取当前登录用户id
     *
     * @param request
     * @return
     */
    private Long getUserId(ServerHttpRequest request) {
        String token = "";
        List<String> tokenList = request.getHeaders().get("token");
        if (null != tokenList) {
            token = tokenList.get(0);
        }
        //获取userid并返回
        if (!StringUtils.isEmpty(token)) {
            return JwtHelper.getUserId(token);
        }
        return null;
    }
}
